import 'mood_type.dart';
import 'mood_record.dart';

/// 情绪统计数据模型类
/// 用于趋势分析页面的数据展示和图表绘制
class MoodStatistics {
  /// 统计时间范围的开始日期
  final DateTime startDate;
  
  /// 统计时间范围的结束日期
  final DateTime endDate;
  
  /// 总记录数
  final int totalRecords;
  
  /// 平均情绪评分
  final double averageMoodScore;
  
  /// 各情绪类型的记录数量
  final Map<MoodType, int> moodTypeCounts;
  
  /// 每日情绪评分数据（用于折线图）
  final Map<DateTime, double> dailyMoodScores;
  
  /// 最常用的标签列表
  final List<TagFrequency> topTags;
  
  /// 情绪变化趋势（上升/下降/稳定）
  final MoodTrend trend;

  /// 构造函数
  const MoodStatistics({
    required this.startDate,
    required this.endDate,
    required this.totalRecords,
    required this.averageMoodScore,
    required this.moodTypeCounts,
    required this.dailyMoodScores,
    required this.topTags,
    required this.trend,
  });

  /// 从情绪记录列表生成统计数据
  /// [records] 情绪记录列表
  /// [startDate] 统计开始日期
  /// [endDate] 统计结束日期
  factory MoodStatistics.fromRecords(
    List<MoodRecord> records,
    DateTime startDate,
    DateTime endDate,
  ) {
    // 过滤指定时间范围内的记录
    final filteredRecords = records.where((record) {
      return record.createdAt.isAfter(startDate.subtract(const Duration(days: 1))) &&
          record.createdAt.isBefore(endDate.add(const Duration(days: 1)));
    }).toList();

    // 计算总记录数
    final totalRecords = filteredRecords.length;

    // 计算平均情绪评分
    double averageMoodScore = 0.0;
    if (totalRecords > 0) {
      final totalScore = filteredRecords.fold<double>(
        0.0,
        (sum, record) => sum + record.moodScore,
      );
      averageMoodScore = totalScore / totalRecords;
    }

    // 统计各情绪类型的数量
    final moodTypeCounts = <MoodType, int>{};
    for (final moodType in MoodType.values) {
      moodTypeCounts[moodType] = filteredRecords
          .where((record) => record.moodType == moodType)
          .length;
    }

    // 计算每日情绪评分
    final dailyMoodScores = <DateTime, double>{};
    final groupedByDate = <String, List<MoodRecord>>{};
    
    for (final record in filteredRecords) {
      final dateKey = record.formattedDate;
      groupedByDate.putIfAbsent(dateKey, () => []).add(record);
    }

    for (final entry in groupedByDate.entries) {
      final date = DateTime.parse(entry.key);
      final dayRecords = entry.value;
      final dayAverage = dayRecords.fold<double>(
        0.0,
        (sum, record) => sum + record.moodScore,
      ) / dayRecords.length;
      dailyMoodScores[date] = dayAverage;
    }

    // 统计标签频率
    final tagCounts = <String, int>{};
    for (final record in filteredRecords) {
      for (final tag in record.tags) {
        tagCounts[tag] = (tagCounts[tag] ?? 0) + 1;
      }
    }

    final topTags = tagCounts.entries
        .map((entry) => TagFrequency(tag: entry.key, count: entry.value))
        .toList()
      ..sort((a, b) => b.count.compareTo(a.count))
      ..take(10).toList();

    // 计算情绪趋势
    final trend = _calculateTrend(dailyMoodScores);

    return MoodStatistics(
      startDate: startDate,
      endDate: endDate,
      totalRecords: totalRecords,
      averageMoodScore: averageMoodScore,
      moodTypeCounts: moodTypeCounts,
      dailyMoodScores: dailyMoodScores,
      topTags: topTags,
      trend: trend,
    );
  }

  /// 计算情绪变化趋势
  static MoodTrend _calculateTrend(Map<DateTime, double> dailyScores) {
    if (dailyScores.length < 2) return MoodTrend.stable;

    final sortedEntries = dailyScores.entries.toList()
      ..sort((a, b) => a.key.compareTo(b.key));

    final firstHalf = sortedEntries.take(sortedEntries.length ~/ 2);
    final secondHalf = sortedEntries.skip(sortedEntries.length ~/ 2);

    final firstAverage = firstHalf.fold<double>(
      0.0,
      (sum, entry) => sum + entry.value,
    ) / firstHalf.length;

    final secondAverage = secondHalf.fold<double>(
      0.0,
      (sum, entry) => sum + entry.value,
    ) / secondHalf.length;

    final difference = secondAverage - firstAverage;
    
    if (difference > 0.5) {
      return MoodTrend.improving;
    } else if (difference < -0.5) {
      return MoodTrend.declining;
    } else {
      return MoodTrend.stable;
    }
  }

  /// 获取最常见的情绪类型
  MoodType? get mostCommonMoodType {
    if (moodTypeCounts.isEmpty) return null;
    
    return moodTypeCounts.entries
        .reduce((a, b) => a.value > b.value ? a : b)
        .key;
  }

  /// 获取情绪类型分布百分比
  Map<MoodType, double> get moodTypePercentages {
    if (totalRecords == 0) return {};
    
    return moodTypeCounts.map(
      (type, count) => MapEntry(type, (count / totalRecords) * 100),
    );
  }

  /// 获取格式化的平均评分字符串
  String get formattedAverageScore {
    return averageMoodScore.toStringAsFixed(1);
  }

  /// 获取趋势描述文本
  String get trendDescription {
    switch (trend) {
      case MoodTrend.improving:
        return '情绪呈上升趋势 📈';
      case MoodTrend.declining:
        return '情绪呈下降趋势 📉';
      case MoodTrend.stable:
        return '情绪保持稳定 ➡️';
    }
  }

  @override
  String toString() {
    return 'MoodStatistics(totalRecords: $totalRecords, averageScore: $formattedAverageScore, trend: $trend)';
  }
}

/// 标签频率数据类
class TagFrequency {
  /// 标签名称
  final String tag;
  
  /// 使用次数
  final int count;

  const TagFrequency({
    required this.tag,
    required this.count,
  });

  @override
  String toString() {
    return 'TagFrequency(tag: $tag, count: $count)';
  }
}

/// 情绪变化趋势枚举
enum MoodTrend {
  /// 情绪改善
  improving,
  /// 情绪下降
  declining,
  /// 情绪稳定
  stable,
}